#include <iostream>
#include <unistd.h>
#include <pthread.h>

pthread_spinlock_t spinlock;    //自旋锁

static int g_ticket = 5000;

void* func(void* args)
{
    char* name = (char*)args;
    while(true)
    {
        
        pthread_spin_lock(&spinlock);
        if(g_ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", name, g_ticket);
            g_ticket--;
            pthread_spin_unlock(&spinlock);
        }
        else
        {
            pthread_spin_unlock(&spinlock);
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_spin_init(&spinlock,PTHREAD_PROCESS_PRIVATE);   
    pthread_t t1,t2,t3,t4,t5;
    pthread_create(&t1,nullptr,func,(void*)"thread-1");
    pthread_create(&t2,nullptr,func,(void*)"thread-2");
    pthread_create(&t3,nullptr,func,(void*)"thread-3");
    pthread_create(&t4,nullptr,func,(void*)"thread-4");
    pthread_create(&t5,nullptr,func,(void*)"thread-5");

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);
    pthread_join(t5,nullptr);

    pthread_spin_destroy(&spinlock);
    return 0;
}